package org.alwayssuper.web.endpoint;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import lombok.extern.slf4j.Slf4j;
import org.alwayssuper.commons.spring.SSEService;
import org.alwayssuper.commons.util.JsonUtils;
import org.alwayssuper.netmc.session.Session;
import org.alwayssuper.protocol.basics.GBTMessage;
import org.alwayssuper.protocol.codec.GBTMessageAdapter;
import org.alwayssuper.protocol.codec.GBTMessageDecoder;
import org.alwayssuper.protocol.codec.GBTMessageEncoder;
import org.alwayssuper.protocol.commons.GBTResponseType;
import org.alwayssuper.protocol.commons.MessageId;

/**
 * @author alwaysSuper
 */
@Slf4j
public class GBTMessagePushAdapter extends GBTMessageAdapter {
    private final SSEService sseService;

    public GBTMessagePushAdapter(GBTMessageEncoder messageEncoder, GBTMessageDecoder messageDecoder, SSEService sseService) {
        super(messageEncoder, messageDecoder);
        this.sseService = sseService;
    }

    @Override
    public void encodeLog(Session session, GBTMessage message, ByteBuf output) {
        int messageId = message.getMessageId();
        String data = MessageId.getName(messageId) + JsonUtils.toJson(message) + ",hex:" + ByteBufUtil.hexDump(output, 0, output.writerIndex());
        sseService.send(message.getClientId(), data);
        if(message.getResponseType() != GBTResponseType.命令){
            log.info("{}\n>>>>>-平台消息应答：{}", session, data);
        }else {
            log.info("{}\n>>>>>-平台指令下行：{}", session, data);
        }
    }

    @Override
    public void decodeLog(Session session, GBTMessage message, ByteBuf input) {
        if (message != null) {
            int messageId = message.getMessageId();
            String data = MessageId.getName(messageId) + JsonUtils.toJson(message) + ",hex:" + ByteBufUtil.hexDump(input, 0, input.writerIndex());
            sseService.send(message.getClientId(), data);
            if(message.getResponseType() != GBTResponseType.命令){
                log.info("{}\n>>>>>-设备消息应答：{}", session, data);
            }else {
                log.info("{}\n>>>>>-设备消息上行：{}", session, data);
            }

            if (!message.isVerified())
                log.error("<<<<<校验码错误session={},payload={}", session, data);
        }
    }
}
